package cn.caplike.demo.spring.security.quickstart.handler;

import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.SimpleUrlAuthenticationSuccessHandler;
import org.springframework.security.web.savedrequest.HttpSessionRequestCache;
import org.springframework.security.web.savedrequest.RequestCache;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 自定义的 SimpleUrlAuthenticationSuccessHandler<br>
 * <ul>
 *  <li>如果启用了 SuccessHandler, 需要手动指定登陆成功后重定向的位置, 借助 {@link HttpSessionRequestCache}</li>
 *  <li>如果没启用 SuccessHandler, 默认登陆成功后就会自动跳转到登陆前的页面</li>
 * </ul>
 *
 * @author LiKe
 * @version 1.0.0
 * @date 2020-04-16 16:41
 */
@Slf4j
@Component
public class CustomSimpleUrlAuthenticationSuccessHandler extends SimpleUrlAuthenticationSuccessHandler {

    private final RequestCache requestCache = new HttpSessionRequestCache();

    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        log.debug("自定义 SuccessHandler :: 登陆成功");
        super.onAuthenticationSuccess(request, response, authentication);
    }

    @Override
    protected String determineTargetUrl(HttpServletRequest request, HttpServletResponse response) {
        log.debug("自定义 SuccessHandler :: 重定向到: {}", requestCache.getRequest(request, response).getRedirectUrl());
        return requestCache.getRequest(request, response).getRedirectUrl();
    }
}
